package com.catering.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSONArray;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.ResourceAccessException;
import javax.annotation.PostConstruct;
import java.time.Duration;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import java.net.InetSocketAddress;
import java.net.Proxy;

@Service
public class AIService {
    
    private static final Logger log = LoggerFactory.getLogger(AIService.class);
    
    @Value("${deepseek.api.key}")
    private String apiKey;
    
    @Value("${deepseek.api.url}")
    private String apiUrl;
    
    @Value("${deepseek.proxy.enabled:false}")
    private boolean proxyEnabled;
    
    @Value("${deepseek.proxy.host:}")
    private String proxyHost;
    
    @Value("${deepseek.proxy.port:0}")
    private int proxyPort;
    
    private final int MAX_RETRIES = 3;
    private final int CONNECT_TIMEOUT = 60000; // 60秒连接超时
    private final int READ_TIMEOUT = 120000;   // 120秒读取超时
    
    @Autowired
    private RestTemplateBuilder restTemplateBuilder;
    
    private RestTemplate restTemplate;
    
    @PostConstruct
    public void init() {
        SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory();
        factory.setConnectTimeout(CONNECT_TIMEOUT);
        factory.setReadTimeout(READ_TIMEOUT);
        
        if (proxyEnabled && !proxyHost.isEmpty() && proxyPort > 0) {
            log.info("配置代理服务器: {}:{}", proxyHost, proxyPort);
            factory.setProxy(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(proxyHost, proxyPort)));
        }
        
        this.restTemplate = new RestTemplate(factory);
    }
    
    public String chatWithAI(String userMessage) {
        int retryCount = 0;
        while (retryCount < MAX_RETRIES) {
            try {
                HttpHeaders headers = new HttpHeaders();
                headers.setContentType(MediaType.APPLICATION_JSON);
                headers.set("Authorization", "Bearer " + apiKey);
                
                JSONObject requestBody = new JSONObject();
                requestBody.put("model", "deepseek-chat");
                requestBody.put("messages", new JSONObject[]{
                    new JSONObject()
                        .fluentPut("role", "user")
                        .fluentPut("content", userMessage)
                });
                
                HttpEntity<String> request = new HttpEntity<>(requestBody.toJSONString(), headers);
                
                log.info("开始处理AI对话请求，尝试次数：{}", retryCount + 1);
                
                ResponseEntity<String> response = restTemplate.postForEntity(apiUrl, request, String.class);
                
                if (response.getStatusCode() == HttpStatus.OK) {
                    JSONObject jsonResponse = JSONObject.parseObject(response.getBody());
                    return jsonResponse.getJSONArray("choices")
                        .getJSONObject(0)
                        .getJSONObject("message")
                        .getString("content");
                }
                
                throw new RuntimeException("API调用失败，状态码：" + response.getStatusCodeValue());
                
            } catch (HttpClientErrorException e) {
                log.error("API调用失败: {}", e.getResponseBodyAsString(), e);
                if (e.getStatusCode() == HttpStatus.UNAUTHORIZED) {
                    return "API密钥验证失败，请检查配置。";
                } else if (e.getStatusCode() == HttpStatus.PAYMENT_REQUIRED) {
                    return "API账户余额不足，请联系管理员充值。";
                }
                return "AI服务调用失败，请稍后重试。";
                
            } catch (ResourceAccessException e) {
                retryCount++;
                log.error("网络连接失败，尝试重试 {}/{}: {}", retryCount, MAX_RETRIES, e.getMessage());
                
                if (retryCount >= MAX_RETRIES) {
                    log.error("达到最大重试次数，请求失败");
                    return "抱歉，AI服务暂时响应较慢，请稍后再试。";
                }
                
                try {
                    // 递增重试延迟
                    Thread.sleep(retryCount * 3000); // 增加重试间隔到3秒
                } catch (InterruptedException ie) {
                    Thread.currentThread().interrupt();
                    break;
                }
            } catch (Exception e) {
                log.error("处理AI对话请求时发生错误: {}", e.getMessage(), e);
                return "系统出现异常，请稍后重试。";
            }
        }
        
        return "抱歉，AI服务暂时不可用，请稍后再试。";
    }
} 